package com.richstone.superset;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class AccpetController {
	private static String url = "http://" + Config.ip + ":" + Config.port;
	private static String host = Config.ip + ":" + Config.port;

	@RequestMapping(path = { "/welcome", "/" })
	public String welcome(HttpServletResponse response) throws Exception {

		String secondRequest = null;
		while (true) {
			Map<String, Object> firstRequest = firstRequest();
			secondRequest = SecondRequest(firstRequest);
			String body = thirdRequest(secondRequest);
			if (body.contains("/superset/profile")) {
				break;
			}
		}

		String session = secondRequest.split("=")[1].trim();
		Cookie cookie = new Cookie("session", session);
		cookie.setHttpOnly(true);
		cookie.setMaxAge(600000000);
		cookie.setPath("/superset/welcome");
		cookie.setDomain(Config.ip);
		response.addCookie(cookie);
		// return "<meta http-equiv=\"refresh\" content=\"0; url=" + url +
		// "/superset/welcome\" />";
		return "redirect:" + url + "/superset/welcome?session=" + session;
	}

	public Map<String, Object> firstRequest() throws Exception {
		Map<String, Object> map = new HashMap<>();
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url + "/login/");
		CloseableHttpResponse response = httpclient.execute(httpGet);
		String string = EntityUtils.toString(response.getEntity());
		Document document = Jsoup.parse(string);
		Element element = document.getElementById("csrf_token");
		String crsf_token = element.attr("value");
		EntityUtils.toString(response.getEntity());
		Header cookie = response.getFirstHeader("Set-Cookie");
		String cookieString = cookie.getValue().split(";")[0].trim();
		map.put("cookie", cookieString);
		map.put("crsf_token", crsf_token);
		return map;

	}

	public String SecondRequest(Map<String, Object> map) throws Exception {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url + "/login/");
		httpPost.addHeader("Referer", url + "/login/");
		httpPost.addHeader("Host", host);
		httpPost.addHeader("Connection", "keep-alive");
		httpPost.addHeader("Cookie", (String) map.get("cookie"));
		httpPost.addHeader("Content-Type", " application/x-www-form-urlencoded");
		httpPost.addHeader("Upgrade-Insecure-Requests", "1");
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("csrf_token", (String) map.get("crsf_token")));
		nvps.add(new BasicNameValuePair("username", Config.username));
		nvps.add(new BasicNameValuePair("password", Config.password));
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
		CloseableHttpResponse response = httpclient.execute(httpPost);
		EntityUtils.toString(response.getEntity());
		Header cookie2 = response.getFirstHeader("Set-Cookie");
		String cookieString = cookie2.getValue().split(";")[0].trim();
		return cookieString;

	}

	public String thirdRequest(String cookie) throws Exception {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpGet httpPost = new HttpGet(url + "/");
		httpPost.addHeader("Referer", url + "/login/");
		httpPost.addHeader("Host", host);
		httpPost.addHeader("Connection", "keep-alive");
		httpPost.addHeader("Cookie", cookie);

		httpPost.addHeader("Upgrade-Insecure-Requests", "1");

		CloseableHttpResponse response = httpclient.execute(httpPost);

		return EntityUtils.toString(response.getEntity());

	}

}
